/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * PanelEntrada.java
 *
 * Created on 08/09/2011, 18:26:49
 */
package modules.estoque.gui.jpanel;

import java.text.ParseException;
import java.util.Date;
import java.util.List;
import javax.swing.JFormattedTextField;
import javax.swing.text.MaskFormatter;
import modules.estoque.exception.EspacoExcedidoPaleteException;
import modules.estoque.exception.EspacoExcedidoRuaException;
import modules.estoque.facade.WMSFacade;
import modules.estoque.gui.custom.LimitedIntegerJTextField;
import modules.estoque.models.dto.Entrada;
import modules.estoque.models.dto.Produto;
import modules.estoque.models.dto.TiposMovimento;
import modules.estoque.security.WMSSession;
import modules.estoque.util.BoxPanel;
import modules.estoque.util.Funcoes;
import modules.estoque.validation.Validation;

/**
 *
 * @author Clezio
 */
public class PanelEntrada extends javax.swing.JPanel {

    private WMSFacade wmsFacade;
    

    /** Creates new form PanelEntrada */
    public PanelEntrada() {
        initComponents();
        wmsFacade = new WMSFacade();
        //Define layout table
//        jTable1.getColumnModel().getColumn(0).setPreferredWidth(44);
//        jTable1.getColumnModel().getColumn(1).setPreferredWidth(116);
//        jTable1.getColumnModel().getColumn(2).setPreferredWidth(52);
//        jTable1.getColumnModel().getColumn(3).setPreferredWidth(144);
//        jTable1.getColumnModel().getColumn(4).setPreferredWidth(306);
//        jTable1.getColumnModel().getColumn(5).setPreferredWidth(48);

    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        wMSLabel1 = new modules.estoque.gui.custom.WMSLabel();
        wMSLabel3 = new modules.estoque.gui.custom.WMSLabel();
        tfCodigo = new modules.estoque.gui.custom.WMSJTextField();
        tfDescricao = new modules.estoque.gui.custom.WMSJTextField();
        btnAdicionar = new modules.estoque.gui.custom.WMSJButton();
        wMSLabel5 = new modules.estoque.gui.custom.WMSLabel();
        tfConfirmar = new modules.estoque.gui.custom.WMSJTextField();
        wMSLabel6 = new modules.estoque.gui.custom.WMSLabel();
        tfData = new javax.swing.JTextField();
        wMSLabel8 = new modules.estoque.gui.custom.WMSLabel();
        tfQuantidade = new LimitedIntegerJTextField(10);
        cbTiposMovimento = new modules.estoque.gui.custom.WMSJComboBox();
        wMSLabel9 = new modules.estoque.gui.custom.WMSLabel();
        wMSLabel10 = new modules.estoque.gui.custom.WMSLabel();
        tfNfEntrada = new LimitedIntegerJTextField(10);
        wMSLabel11 = new modules.estoque.gui.custom.WMSLabel();
        tfPrecoCusto = new modules.estoque.gui.custom.WMSJTextField();
        wMSLabel12 = new modules.estoque.gui.custom.WMSLabel();
        tfPrecoVenda = new modules.estoque.gui.custom.WMSJTextField();
        btnPesquisar = new modules.estoque.gui.custom.WMSJButton();

        setBackground(new java.awt.Color(238, 238, 238));
        addAncestorListener(new javax.swing.event.AncestorListener() {
            public void ancestorMoved(javax.swing.event.AncestorEvent evt) {
            }
            public void ancestorAdded(javax.swing.event.AncestorEvent evt) {
                formAncestorAdded(evt);
            }
            public void ancestorRemoved(javax.swing.event.AncestorEvent evt) {
            }
        });

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel1.setText("Entrada");

        wMSLabel1.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        wMSLabel1.setText("Data:");

        wMSLabel3.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        wMSLabel3.setText("Código:");

        tfCodigo.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                tfCodigoFocusLost(evt);
            }
        });
        tfCodigo.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                tfCodigoKeyPressed(evt);
            }
        });

        tfDescricao.setEditable(false);
        tfDescricao.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                tfDescricaoKeyPressed(evt);
            }
        });

        btnAdicionar.setText("Registrar");
        btnAdicionar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAdicionarActionPerformed(evt);
            }
        });

        wMSLabel5.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        wMSLabel5.setText("Confimar dados:");

        tfConfirmar.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                tfConfirmarKeyPressed(evt);
            }
            public void keyReleased(java.awt.event.KeyEvent evt) {
                tfConfirmarKeyReleased(evt);
            }
        });

        wMSLabel6.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        wMSLabel6.setText("(S) ou (N)");

        try{
            tfData = new JFormattedTextField(new MaskFormatter("##/##/####"));
        }catch(Exception e){}
        tfData.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                tfDataKeyPressed(evt);
            }
        });

        wMSLabel8.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        wMSLabel8.setText("Quantidade:");

        tfQuantidade.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                tfQuantidadeKeyPressed(evt);
            }
        });

        cbTiposMovimento.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        cbTiposMovimento.setFont(new java.awt.Font("Tahoma", 1, 10)); // NOI18N
        cbTiposMovimento.setMaximumSize(new java.awt.Dimension(51, 18));
        cbTiposMovimento.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                cbTiposMovimentoItemStateChanged(evt);
            }
        });
        cbTiposMovimento.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                cbTiposMovimentoKeyPressed(evt);
            }
        });

        wMSLabel9.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        wMSLabel9.setText("Natureza:");

        wMSLabel10.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        wMSLabel10.setText("Nota Fiscal:");

        tfNfEntrada.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                tfNfEntradaKeyPressed(evt);
            }
        });

        wMSLabel11.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        wMSLabel11.setText("Preço Custo:");

        tfPrecoCusto.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                tfPrecoCustoKeyPressed(evt);
            }
        });

        wMSLabel12.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        wMSLabel12.setText("Nota Venda:");

        tfPrecoVenda.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                tfPrecoVendaKeyPressed(evt);
            }
        });

        btnPesquisar.setText("Pesquisar");
        btnPesquisar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnPesquisarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 780, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap())
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(23, 23, 23)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createSequentialGroup()
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                            .addComponent(wMSLabel9, javax.swing.GroupLayout.PREFERRED_SIZE, 73, javax.swing.GroupLayout.PREFERRED_SIZE)
                                            .addComponent(wMSLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 73, javax.swing.GroupLayout.PREFERRED_SIZE))
                                        .addGap(0, 0, Short.MAX_VALUE))
                                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                            .addComponent(wMSLabel8, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                            .addComponent(wMSLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                            .addGroup(layout.createSequentialGroup()
                                                .addComponent(tfCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                .addGap(6, 6, 6)
                                                .addComponent(tfDescricao, javax.swing.GroupLayout.PREFERRED_SIZE, 267, javax.swing.GroupLayout.PREFERRED_SIZE))
                                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                                .addComponent(tfData, javax.swing.GroupLayout.Alignment.LEADING)
                                                .addComponent(cbTiposMovimento, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 129, Short.MAX_VALUE))
                                            .addComponent(tfQuantidade, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE)))
                                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                            .addGroup(layout.createSequentialGroup()
                                                .addComponent(wMSLabel11, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                                .addComponent(tfPrecoCusto, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE))
                                            .addGroup(layout.createSequentialGroup()
                                                .addComponent(wMSLabel10, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                                .addComponent(tfNfEntrada, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE))
                                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                                .addComponent(wMSLabel12, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                                .addComponent(tfPrecoVenda, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE)))
                                        .addGap(273, 273, 273))))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(wMSLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(btnAdicionar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(tfConfirmar, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(wMSLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                                .addGap(0, 0, Short.MAX_VALUE)))
                        .addGap(18, 18, 18)
                        .addComponent(btnPesquisar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(211, 211, 211))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 8, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(wMSLabel9, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(cbTiposMovimento, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(wMSLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(tfData, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(wMSLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 17, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(tfCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(tfDescricao, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(btnPesquisar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(wMSLabel8, javax.swing.GroupLayout.PREFERRED_SIZE, 17, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(tfQuantidade, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(wMSLabel10, javax.swing.GroupLayout.PREFERRED_SIZE, 17, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(tfNfEntrada, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(wMSLabel11, javax.swing.GroupLayout.PREFERRED_SIZE, 17, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(tfPrecoCusto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(wMSLabel12, javax.swing.GroupLayout.PREFERRED_SIZE, 17, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(tfPrecoVenda, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(4, 4, 4)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(2, 2, 2)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addComponent(wMSLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 17, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(1, 1, 1))
                            .addComponent(wMSLabel5, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 17, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addComponent(tfConfirmar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(btnAdicionar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(163, 163, 163))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void tfCodigoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tfCodigoKeyPressed
        if (evt.getKeyCode() == evt.VK_ENTER) {
            tfQuantidade.requestFocus();
        } else if (evt.getKeyCode() == evt.VK_ESCAPE) {
            tfCodigo.setText("");
        }
    }//GEN-LAST:event_tfCodigoKeyPressed

    private void tfDescricaoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tfDescricaoKeyPressed
        // TODO add your handling code here:
    }//GEN-LAST:event_tfDescricaoKeyPressed

    private void btnAdicionarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAdicionarActionPerformed
        String confirm = tfConfirmar.getText();
        if (confirm.toUpperCase().equals("S")) {
            save();
        } else if (confirm.toUpperCase().equals("N")) {
            clearFields();
        } else {
            BoxPanel.showMessageDialog(null, "A confirmação um campo obrigatório.");
            tfConfirmar.setText("");
            tfConfirmar.requestFocus();
        }
}//GEN-LAST:event_btnAdicionarActionPerformed

    private void tfCodigoFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_tfCodigoFocusLost
        if (tfCodigo.getText().length() > 0) {
            Produto produto = wmsFacade.obterProdutoByCodigo(tfCodigo.getText());
            if (produto == null) {
                BoxPanel.showMessageDialog(null, "Produto não encontrado");
                tfCodigo.setText("");
                tfCodigo.requestFocus();
                tfDescricao.setText("");
            } else {
                tfDescricao.setText(produto.getDescricao());
                tfQuantidade.requestFocus();
            }
        } else {
            tfDescricao.setText("");
        }
    }//GEN-LAST:event_tfCodigoFocusLost

    private void tfConfirmarKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tfConfirmarKeyPressed
        if (evt.getKeyCode() == evt.VK_ENTER) {
            String confirm = tfConfirmar.getText();
            if (confirm.toUpperCase().equals("S")) {
                save();
            } else if (confirm.toUpperCase().equals("N")) {
                clearFields();
            } else {
                BoxPanel.showMessageDialog(null, "A confirmação um campo obrigatório.");
                tfConfirmar.setText("");
                tfConfirmar.requestFocus();
            }
        } else if (evt.getKeyCode() == evt.VK_ESCAPE) {
            tfConfirmar.setText("");
            tfPrecoVenda.requestFocus();
        }
    }//GEN-LAST:event_tfConfirmarKeyPressed

    private void tfConfirmarKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tfConfirmarKeyReleased
        if (tfConfirmar.getText().length() > 0) {
            tfConfirmar.setText(tfConfirmar.getText().substring(0, 1));
        }
    }//GEN-LAST:event_tfConfirmarKeyReleased

    private void formAncestorAdded(javax.swing.event.AncestorEvent evt) {//GEN-FIRST:event_formAncestorAdded
        clearAllFields();
        tfData.setText(Funcoes.dateToString(new Date()));
        preencheCbTiposMovimento(wmsFacade.obterTiposMovimentos("from TiposMovimento where natureza = 'E' order by nome"));
    }//GEN-LAST:event_formAncestorAdded

    private void tfDataKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tfDataKeyPressed
        if (evt.getKeyCode() == evt.VK_ENTER) {
            tfCodigo.requestFocus();
        } else if (evt.getKeyCode() == evt.VK_ESCAPE) {
            tfData.setText("");
            cbTiposMovimento.requestFocus();
        }
    }//GEN-LAST:event_tfDataKeyPressed

    private void tfQuantidadeKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tfQuantidadeKeyPressed
        if (evt.getKeyCode() == evt.VK_ENTER) {
            tfNfEntrada.requestFocus();
        } else if (evt.getKeyCode() == evt.VK_ESCAPE) {
            tfCodigo.requestFocus();
            tfQuantidade.setText("");
        }
    }//GEN-LAST:event_tfQuantidadeKeyPressed

    private void cbTiposMovimentoItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_cbTiposMovimentoItemStateChanged
        
    }//GEN-LAST:event_cbTiposMovimentoItemStateChanged

    private void cbTiposMovimentoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_cbTiposMovimentoKeyPressed
        if (evt.getKeyCode() == evt.VK_ENTER) {
            tfData.requestFocus();
        }
    }//GEN-LAST:event_cbTiposMovimentoKeyPressed

    private void tfNfEntradaKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tfNfEntradaKeyPressed
        if (evt.getKeyCode() == evt.VK_ENTER) {
            tfPrecoCusto.requestFocus();
        } else if (evt.getKeyCode() == evt.VK_ESCAPE) {
            tfNfEntrada.setText("");
            tfQuantidade.requestFocus();
        }
    }//GEN-LAST:event_tfNfEntradaKeyPressed

    private void tfPrecoCustoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tfPrecoCustoKeyPressed
        if (evt.getKeyCode() == evt.VK_ENTER) {
            tfPrecoVenda.requestFocus();
        } else if (evt.getKeyCode() == evt.VK_ESCAPE) {
            tfPrecoCusto.setText("");
            tfNfEntrada.requestFocus();
        }
    }//GEN-LAST:event_tfPrecoCustoKeyPressed

    private void tfPrecoVendaKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tfPrecoVendaKeyPressed
        if (evt.getKeyCode() == evt.VK_ENTER) {
            tfConfirmar.requestFocus();
        } else if (evt.getKeyCode() == evt.VK_ESCAPE) {
            tfPrecoVenda.setText("");
            tfPrecoCusto.requestFocus();
        }
    }//GEN-LAST:event_tfPrecoVendaKeyPressed

    private void btnPesquisarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPesquisarActionPerformed
        FrameProdutoPesquisa frame = new FrameProdutoPesquisa(tfCodigo, tfDescricao, tfQuantidade);
        frame.setVisible(true);
    }//GEN-LAST:event_btnPesquisarActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private modules.estoque.gui.custom.WMSJButton btnAdicionar;
    private modules.estoque.gui.custom.WMSJButton btnPesquisar;
    private modules.estoque.gui.custom.WMSJComboBox cbTiposMovimento;
    private javax.swing.JLabel jLabel1;
    private modules.estoque.gui.custom.WMSJTextField tfCodigo;
    private modules.estoque.gui.custom.WMSJTextField tfConfirmar;
    private javax.swing.JTextField tfData;
    private modules.estoque.gui.custom.WMSJTextField tfDescricao;
    private modules.estoque.gui.custom.WMSJTextField tfNfEntrada;
    private modules.estoque.gui.custom.WMSJTextField tfPrecoCusto;
    private modules.estoque.gui.custom.WMSJTextField tfPrecoVenda;
    private modules.estoque.gui.custom.WMSJTextField tfQuantidade;
    private modules.estoque.gui.custom.WMSLabel wMSLabel1;
    private modules.estoque.gui.custom.WMSLabel wMSLabel10;
    private modules.estoque.gui.custom.WMSLabel wMSLabel11;
    private modules.estoque.gui.custom.WMSLabel wMSLabel12;
    private modules.estoque.gui.custom.WMSLabel wMSLabel3;
    private modules.estoque.gui.custom.WMSLabel wMSLabel5;
    private modules.estoque.gui.custom.WMSLabel wMSLabel6;
    private modules.estoque.gui.custom.WMSLabel wMSLabel8;
    private modules.estoque.gui.custom.WMSLabel wMSLabel9;
    // End of variables declaration//GEN-END:variables

    private void save() {
        int quantidade = 0;
        try{
            quantidade = Integer.parseInt(tfQuantidade.getText());
        }catch(Exception e){}
        
        Date date = null;
        try {
            date = Funcoes.stringToDate(tfData.getText());
            if(date.after(new Date())){
                Validation.getInstance().addErros("data", "A data nãoo pode ser superior a data atual.");
            }
        } catch (ParseException ex) {
            if(tfData.getText().equals("  /  /    ")){
                Validation.getInstance().addErros("data", "Data é um campo obrigatório.");
            }else{
                Validation.getInstance().addErros("data", "A data informada é inválida.");
            }
        }
       
        Produto produto = wmsFacade.obterProdutoByCodigo(tfCodigo.getText());
        if (produto == null) {
            BoxPanel.showMessageDialog(null, "Produto inválido");
            return;
        }

        //####
        Entrada entrada = new Entrada();
        entrada.setProduto(produto);
        entrada.setQuantidade(quantidade);
        entrada.setDataEntrada(date);
        entrada.setUsuario(WMSSession.getInstance().getUser());
        entrada.setTiposMovimento((TiposMovimento) cbTiposMovimento.getSelectedItem());
        entrada.setNota_fiscal((!tfNfEntrada.getText().equals("") ? Integer.parseInt(tfNfEntrada.getText()) : null));
        entrada.setCancelado(false);
        try{
            entrada.setPrecoCusto(new Double(tfPrecoCusto.getText().replace(",", ".")));
            entrada.setPrecoVenda(new Double(tfPrecoVenda.getText().replace(",", ".")));
        }catch(Exception e){
            BoxPanel.showMessageDialog(null, "Preço informado é inválido.");
            return;
        }
        
        try {
            if (wmsFacade.registrarEntrada(entrada)) {
                BoxPanel.showMessageDialog(null, "Entrada registrada com sucesso!");
                clearFields();
            }
        } catch (EspacoExcedidoPaleteException ex) {
            BoxPanel.showMessageDialog(null, ex.getMessage());
            tfConfirmar.setText("");
            tfConfirmar.requestFocus();
        } catch (EspacoExcedidoRuaException ex) {
            BoxPanel.showMessageDialog(null, ex.getMessage());
        }
    }

    private void clearFields() {
        tfCodigo.setText("");
        tfDescricao.setText("");
        tfQuantidade.setText("");
        tfConfirmar.setText("");
        tfPrecoCusto.setText("");
        tfPrecoVenda.setText("");
        tfNfEntrada.setText("");
        tfCodigo.requestFocus();
    }

    private void clearAllFields() {
        clearFields();
    }

//    private void listarEnderecamento(List<Enderecamento> enderecamentos) {
//        if (enderecamentos != null) {
//            DefaultTableModel modelo = (DefaultTableModel) jTable1.getModel();
//            modelo.setNumRows(0);
//            for (int i = 0; i < enderecamentos.size(); i++) {
//                int id = enderecamentos.get(i).getId();
//                String rua = enderecamentos.get(i).getPalete().getRua().getNome();
//                Integer palete = enderecamentos.get(i).getPalete().getId();
//                String codigo = enderecamentos.get(i).getProduto().getCodigo();
//                String descricao = enderecamentos.get(i).getProduto().getDescricao();
//                Integer quantidade = enderecamentos.get(i).getQuantidade();
//                modelo.addRow(new Object[]{
//                            id, rua, palete, codigo, descricao, quantidade
//                        });
//            }
//        }
//    }

    private void preencheCbTiposMovimento(List<TiposMovimento> lista){
        cbTiposMovimento.removeAllItems();
        for (int i= 0; i < lista.size(); i++) {
            cbTiposMovimento.addItem(lista.get(i));
            if(lista.get(i).getId() == 1){
                cbTiposMovimento.setSelectedIndex(i);
            }
        }
    }
}
